package com.jiyi.view;

import java.util.HashMap;
import java.util.Map;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.hyphenate.easeui.EaseConstant;
import com.jiyi.bean.main.NewsListJson.NewsBean;
import com.jiyi.bean.zone.QunZuDetailJson.QunZuDetail;
import com.jiyi.bean.zone.ZoneHuoDongBean;
import com.jiyi.bean.zone.ZoneQunZuBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.ClouldChatType;
import com.jiyi.easemob.view.EasemobChatActivity;
import com.jiyi.event.HuoDongListEvent;
import com.jiyi.event.HuoDongStatuEvent;
import com.jiyi.event.QunZuListEvent;
import com.jiyi.inteface.HuoDongPopInterface;
import com.jiyi.inteface.QunZuPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.CircleProgressView;
import com.swift.base.ApplicationBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DateUtils;
import com.swift.utils.GlideUtil;
import com.swift.widget.TranslucentImageView;

public class QunZuPopView {

	private QunZuPopInterface mQunZuPopInterface;
	private Context context;
	private PopupWindow mPopupWindow;
	private TextView tvQunZuName;
	private TextView tvCreator;
	private TextView tvQunZuCreateDate;
	private TextView tvQunZuJianJie;
	private TextView tvQunZuNum;
	private CircleProgressView memberBiLi;
	private TextView tvHuoDongNum;
	private CircleProgressView huoDongBiLi;
	private CardView cvLastQunZu;
	private TranslucentImageView ivHuoDongLogo;
	private ImageView ivQunZuLogo;
	private TextView tvTitle;
	private TextView tvStartDate;
	private TextView tvEndDate;
	private TextView tvAddress;
	private TextView tvJoin;

	TextView tvState;
	RelativeLayout rlTip;
	TextView tvTip;
	TextView tvGoTo;
	ProgressBar progressBar;

	// private ZoneQunZuBean zoneQunZuBean;
	private QunZuDetail qunZuDetail;

	// 审核提示
	private String checkString = "您的加群申请已发送，请等待该群群组审核";
	// 加群完成提示
	private String joinString = "您的加群申请已发送，已加入该群";

	public QunZuPopView(Context context, QunZuPopInterface qunZuPopInterface) {
		this.context = context;
		this.mQunZuPopInterface = qunZuPopInterface;
		init();
	}

	/**
	 * @author: HYM
	 * @Title: init
	 * @Description: TODO(初始化一个新的PopWindow)
	 * @param:
	 * @return: void
	 * @return: 2017-5-5
	 * @throws
	 */
	private void init() {
		// 得到内容布局
		View view = LayoutInflater.from(context).inflate(R.layout.pop_qunzu,
				null);

		// 取消按钮
		ImageView ivClose = (ImageView) view.findViewById(R.id.ivClose);
		ivClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mQunZuPopInterface.OnQZCancleListener();
				hidePopWindow();
			}
		});

		// 确定按钮
		tvState = (TextView) view.findViewById(R.id.tvState);

		rlTip = (RelativeLayout) view.findViewById(R.id.rlTip);
		rlTip.setVisibility(View.GONE);
		tvTip = (TextView) view.findViewById(R.id.tvTip);
		tvGoTo = (TextView) view.findViewById(R.id.tvGoTo);
		cvLastQunZu = (CardView) view.findViewById(R.id.cvLastQunZu);
		ivHuoDongLogo = (TranslucentImageView) view.findViewById(R.id.ivHuoDongLogo);
		ivQunZuLogo = (ImageView) view.findViewById(R.id.ivQunZuLogo);
		tvTitle = (TextView) view.findViewById(R.id.tvTitle);
		tvStartDate = (TextView) view.findViewById(R.id.tvStartDate);
		tvEndDate = (TextView) view.findViewById(R.id.tvEndDate);
		tvAddress = (TextView) view.findViewById(R.id.tvAddress);
		tvJoin = (TextView) view.findViewById(R.id.tvJoin);

		tvQunZuName = (TextView) view.findViewById(R.id.tvQunZuName);
		tvCreator = (TextView) view.findViewById(R.id.tvCreator);
		tvQunZuCreateDate = (TextView) view
				.findViewById(R.id.tvQunZuCreateDate);
		tvQunZuJianJie = (TextView) view.findViewById(R.id.tvQunZuJianJie);
		tvQunZuNum = (TextView) view.findViewById(R.id.tvQunZuNum);
		memberBiLi = (CircleProgressView) view.findViewById(R.id.memberBiLi);
		tvHuoDongNum = (TextView) view.findViewById(R.id.tvHuoDongNum);
		huoDongBiLi = (CircleProgressView) view.findViewById(R.id.huoDongBiLi);
		progressBar = (ProgressBar) view.findViewById(R.id.progressBar);

		mPopupWindow = new PopupWindow(view,
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		mPopupWindow.setFocusable(true); // 让popWindow获取焦点
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable()); // 设置popWindow背景颜色
		mPopupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
		mPopupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				hidePopWindow();
			}
		});
	}

	/**
	 * @author: HYM
	 * @Title: showPopWindow
	 * @Description: TODO(显示弹出菜单)
	 * @param:
	 * @return: void
	 * @return: 2017-4-26
	 * @throws
	 */
	public void showPopWindow(QunZuDetail qunZuDetail) {
		
		initView();
		
		if (null != qunZuDetail) {
			// setZoneQunZuBean(zoneQunZuBean);
			setQunZuDetail(qunZuDetail);
			final ZoneQunZuBean zoneQunZuBean = qunZuDetail.getGroupInfo();
			initTip(zoneQunZuBean);
			
			GlideUtil.load(context, zoneQunZuBean.getGroup_head(), ivQunZuLogo);
			tvQunZuName.setText(zoneQunZuBean.getName());
			tvCreator.setText(zoneQunZuBean.getGroup_manager_nickname());
			tvQunZuJianJie.setText(zoneQunZuBean.getIntroduction());
			tvQunZuCreateDate.setText("本群创建于" + zoneQunZuBean.getCreate_time());
			tvHuoDongNum.setText("活动：" + zoneQunZuBean.getAct_can_join_num()
					+ "/" + zoneQunZuBean.getAct_all_num());
			// 判断总数为0的情况
			if (zoneQunZuBean.getAct_all_num().equals("0")) {
				huoDongBiLi.setProgress(0);
			} else {
				huoDongBiLi
						.setProgress(100
								* (Float.parseFloat(zoneQunZuBean
										.getAct_can_join_num()))
								/ Float.parseFloat(zoneQunZuBean
										.getAct_all_num()));
			}
			// 判断总数为0的情况
			tvQunZuNum.setText("人数：" + zoneQunZuBean.getGroupUserNum() + "/"
					+ zoneQunZuBean.getMax_user_num());
			if (zoneQunZuBean.getMax_user_num().equals("0")) {
				memberBiLi.setProgress(0);
			} else {
				memberBiLi.setProgress(100 * (Float.parseFloat(zoneQunZuBean
						.getGroupUserNum()) / Float.parseFloat(zoneQunZuBean
						.getMax_user_num())));
			}
			huoDongBiLi.setCircleColor(Color.GREEN);

			// 获取最新群活动
			ZoneHuoDongBean zoneHuoDongBean = qunZuDetail.getActivityInfo();
			if (null == zoneHuoDongBean) {
				cvLastQunZu.setVisibility(View.GONE);
			} else {
				cvLastQunZu.setVisibility(View.VISIBLE);
				GlideUtil.load(context, zoneHuoDongBean.getCover(),
						ivHuoDongLogo);
				ivHuoDongLogo.setTextString(zoneHuoDongBean.getAttendPer()+"人参与");
				tvTitle.setText(zoneHuoDongBean.getTheme());
				tvStartDate.setText(DateUtils.fmtDateToStr(zoneHuoDongBean.getStart_time(), DateUtils.YMD_FORMAT));
				tvEndDate.setText(DateUtils.fmtDateToStr(zoneHuoDongBean.getEnd_time(), DateUtils.YMD_FORMAT));
				tvAddress.setText(zoneHuoDongBean.getAddress());
				int status = zoneHuoDongBean.getFlag();
				switch (status) {
				case 1:
					tvJoin.setText("等待报名");
					tvJoin.setBackgroundResource(R.drawable.round_huodong_state_small_blue);
					break;
				case 2:
					tvJoin.setText("可参与");
					tvJoin.setBackgroundResource(R.drawable.round_huodong_state_small_blue);
					break;
				case 3:
					tvJoin.setText("待开始");
					tvJoin.setBackgroundResource(R.drawable.round_huodong_state_small_blue);
					break;
				case 4:
					tvJoin.setText("进行中");
					tvJoin.setBackgroundResource(R.drawable.round_huodong_state);
					break;
				case 5:
					tvJoin.setText("活动结束");
					tvJoin.setBackgroundResource(R.drawable.round_huodong_state_gray);
					break;
				case 6:
					tvJoin.setText("活动取消");
					tvJoin.setBackgroundResource(R.drawable.round_huodong_state_gray);
					break;
				default:
					break;
				}
			}
			
			tvState.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					tvState.setVisibility(View.GONE);
					mQunZuPopInterface.OnQZSureListener();
					joinQunZu(zoneQunZuBean.getId());
				}

			});
			
			tvGoTo.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent2 = new Intent(v.getContext(),
							EasemobChatActivity.class);
					intent2.putExtra(ClouldChatType.INTENT_USER_PIC,
							zoneQunZuBean.getGroup_head());
					intent2.putExtra("id", zoneQunZuBean.getId());
					intent2.putExtra("name", zoneQunZuBean.getName());
					intent2.putExtra("headurl", zoneQunZuBean.getGroup_head());
					intent2.putExtra("type", String.valueOf(108));
					intent2.putExtra("easemobgid", zoneQunZuBean.getHx_group_id());
					intent2.putExtra(ClouldChatType.INTENT_Group_Id,
							zoneQunZuBean.getHx_group_id());
					intent2.putExtra("easeMobChatType", EaseConstant.CHATTYPE_GROUP);
					intent2.putExtra(ClouldChatType.INTENT_MSG_TP,
							ClouldChatType.TYPE_NEIGHBOUR);
					v.getContext().startActivity(intent2);
					hidePopWindow();
				}
			});
		}

		mPopupWindow
				.showAtLocation(new TextView(context), Gravity.CENTER, 0, 0);
		backgroundAlpha(0.5F);
		mQunZuPopInterface.OnQZShowListener();
	}

	/**
	 * @author: HYM
	 * @Title: hidePopWindow
	 * @Description: TODO(关闭弹出菜单)
	 * @param:
	 * @return: void
	 * @return: 2017-4-26
	 * @throws
	 */
	public void hidePopWindow() {
		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
		backgroundAlpha(1F);
		mQunZuPopInterface.OnQZHideListener();
	}

	/**
	 * 设置添加屏幕的背景透明度
	 * 
	 * @param bgAlpha
	 */
	public void backgroundAlpha(float bgAlpha) {
		Activity activity = (Activity) context;
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = bgAlpha; // 0.0-1.0
		activity.getWindow().setAttributes(lp);
		activity.getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_DIM_BEHIND);
	}

	public QunZuDetail getQunZuDetail() {
		return qunZuDetail;
	}

	public void setQunZuDetail(QunZuDetail qunZuDetail) {
		this.qunZuDetail = qunZuDetail;
	}

	// public ZoneQunZuBean getZoneQunZuBean() {
	// return zoneQunZuBean;
	// }
	//
	// public void setZoneQunZuBean(ZoneQunZuBean zoneQunZuBean) {
	// this.zoneQunZuBean = zoneQunZuBean;
	// }
	
	void joinQunZu(final String id) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		progressBar.setVisibility(View.VISIBLE);
		VolleyRequest.StringRequestPost(context, WebApi.ZONE_QUNZU_JOIN, "",
				params, new StringInterface(context) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								EventBus.getDefault().post(new QunZuListEvent(QunZuListEvent.MY_QUNZU_FRAGMENT));
								EventBus.getDefault().post(new QunZuListEvent(QunZuListEvent.ALL_QUNZU_NEW));
								//根据公开还是私有设置加入的提示文字
								if (qunZuDetail.getGroupInfo().getGroup_type().equals("0")) {
									tvTip.setText(joinString);
								}
								else {
									tvTip.setText(checkString);
								}
								handleTip(qunZuDetail.getGroupInfo().getGroup_type());
							} else {
								tvState.setVisibility(View.VISIBLE);
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							progressBar.setVisibility(View.GONE);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						tvState.setVisibility(View.VISIBLE);
						progressBar.setVisibility(View.GONE);
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});

	}

	/**   
	 * @author: HYM 
	 * @Title: handleTip   
	 * @Description: TODO(处理下部的消息提示)   
	 * @param group_type 群性质（0：公开群 1：私有群）
	 * @date: 2017-7-21
	 */  
	void handleTip(String group_type)
	{
//		if (isLoading) {
//			progressBar.setVisibility(View.VISIBLE);
//		}
//		else {
//			progressBar.setVisibility(View.GONE);
//		}
		
		switch (Integer.parseInt(group_type)) {
		case 0:
			tvState.setVisibility(View.GONE);
			rlTip.setVisibility(View.VISIBLE);
			break;
		case 1:
			tvState.setVisibility(View.GONE);
			tvGoTo.setVisibility(View.GONE);
			rlTip.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
	}
	
	/**   
	 * @author: HYM 
	 * @Title: handleTip   
	 * @Description: TODO(处理下部的消息提示)   
	 * @param group_type 群性质（0：公开群 1：私有群）
	 * @date: 2017-7-21
	 */  
	void initTip(ZoneQunZuBean zoneQunZuBean)
	{
		
		if (!zoneQunZuBean.getIs_in_group()) {
			//判断当前用户加入群的状态 0待审核 1通过 2不通过 3未申请
			switch (zoneQunZuBean.getIs_status()) {
			case 0:
				tvState.setVisibility(View.GONE);
				rlTip.setVisibility(View.VISIBLE);
				tvTip.setText(checkString);
				tvGoTo.setVisibility(View.GONE);
				break;
			case 3:
				tvState.setVisibility(View.VISIBLE);
				rlTip.setVisibility(View.GONE);
				break;
			default:
				break;
			}
		}
		
	}
	
	/**   
	 * @author: HYM 
	 * @Title: initView   
	 * @Description: TODO(因为POP是一次性加载的，所以每次进来时，需要复位下底部提示状态)    void 
	 * @date: 2017-7-21
	 */  
	void initView()
	{
		tvState.setVisibility(View.VISIBLE);
		rlTip.setVisibility(View.GONE);
	}
}
